/************************************************************
 *  * Hyphenate CONFIDENTIAL
 * __________________
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of Hyphenate Inc.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Hyphenate Inc.
 */

#import "ConversationListController.h"

#import "ChatViewController.h"
#import "EMSearchBar.h"
#import "EMSearchDisplayController.h"
#import "RobotManager.h"
#import "RobotChatViewController.h"
#import "UserProfileManager.h"
#import "RealtimeSearchUtil.h"
#import "RedPacketChatViewController.h"
#import "ChatDemoHelper.h"

#import "MainViewController.h"



@implementation EMConversation (search)

//根据用户昵称,环信机器人名称,群名称进行搜索
- (NSString*)showName
{
    if (self.type == EMConversationTypeChat) {
        if ([[RobotManager sharedInstance] isRobotWithUsername:self.conversationId]) {
            return [[RobotManager sharedInstance] getRobotNickWithUsername:self.conversationId];
        }
        return [[UserProfileManager sharedInstance] getNickNameWithUsername:self.conversationId];
    } else if (self.type == EMConversationTypeGroupChat) {
        if ([self.ext objectForKey:@"subject"] || [self.ext objectForKey:@"isPublic"]) {
            return [self.ext objectForKey:@"subject"];
        }
    }
    return self.conversationId;
}

@end

@interface ConversationListController ()<EaseConversationListViewControllerDelegate, EaseConversationListViewControllerDataSource,UISearchDisplayDelegate, UISearchBarDelegate,UIScrollViewDelegate>
{
    BOOL isFromStart;
}

@property (nonatomic,assign)CGFloat contentHeight;

@property (strong, nonatomic)  UIView *adsView;

@property (nonatomic,assign) int cur;

//轮播图变量
@property(nonatomic, strong)UIScrollView  *scrollView;      //声明一个UIScrollView
@property(nonatomic, strong)UIPageControl *pageControl;     //声明一个UIPageControl
@property(nonatomic, strong)NSMutableArray  *arrayImages;          //存放图片的数组
@property(nonatomic, strong)NSMutableArray *viewController; //存放UIViewController的可变数组
@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,strong)UIView *rxView;



@property (nonatomic,strong)NSMutableArray *docterListSource;
@property (nonatomic,assign)NSInteger docterCount ;
@property (nonatomic,strong)UIView *shoppingView;//商品详情View
@property (nonatomic,assign)CGFloat *shoppingHeight;//商品详情高度



//原来的



@property (nonatomic, strong) UIView *networkStateView;
@property (nonatomic, strong) EMSearchBar           *searchBar;

@property (strong, nonatomic) EMSearchDisplayController *searchController;

@property (strong,nonatomic) UIView *systemView;

@property (nonatomic,strong) UIView * headView;//头部

@end


@implementation ConversationListController

-(UIView *)systemView{
    if (!_systemView) {
        _systemView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, mainScreenSize.width, mainScreenSize.height-114)];
        _systemView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_systemView];
        
        UILabel *headLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, -0.5, mainScreenSize.width, 1)];
        headLabel.backgroundColor = RGB(199, 199, 199);
        [_systemView addSubview:headLabel];
    }
    return _systemView;
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RGB(249, 249, 249);
    
    //设置轮播图
    [self drawView];
    [self initData];
    
    //这是列表标题
    [self setTableViewTitle];
    
    [self setupBarButtonItem];
    
    
    self.showRefreshHeader = YES;
    self.delegate = self;
    self.dataSource = self;
    
    [self tableViewDidTriggerHeaderRefresh];
    //
    //       self.title = @"个人信息";
    
    self.tableView.frame = CGRectMake(0, self.adsView.frame.size.height + 40, kScreen_Width, kScreen_Height-self.adsView.frame.size.height);
    
    [self networkStateView];
    
    //    [self searchController];
    
    [self removeEmptyConversationsFromDB];
}

-(void)setTableViewTitle{
    //标题
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,self.adsView.frame.size.height,kScreen_Width,40)];
    nameLabel.numberOfLines = 1;
    nameLabel.clipsToBounds = YES;
    nameLabel.layer.cornerRadius = 4;
    nameLabel.textAlignment = NSTextAlignmentLeft;
    nameLabel.font = [UIFont systemFontOfSize:15];
    nameLabel.backgroundColor = RGBJ(239);
    nameLabel.textColor = RGB(85, 204, 84);
    nameLabel.text = @"  全部消息";
    [self.view addSubview:nameLabel];
    
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,self.adsView.frame.size.height + 39.5,kScreen_Width,0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
}

- (void)setupBarButtonItem
{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 30, 25, 25)];
    [backButton setImage:[UIImage imageNamed:@"xiangyou.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view  addSubview:backButton];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(kScreen_Width/2 - 40, 25, 80, 40)];
    title.textAlignment = NSTextAlignmentCenter;
    title.font = [UIFont systemFontOfSize:16];
    title.textColor = RGBJ(77);
    title.text = @"名医咨询";
    [self.view addSubview:title];
    //    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    //    [self.navigationItem setLeftBarButtonItem:backItem];
}

-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self refresh];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)removeEmptyConversationsFromDB
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (!conversation.latestMessage || (conversation.type == EMConversationTypeChatRoom)) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            
            [needRemoveConversations addObject:conversation];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EMClient sharedClient].chatManager deleteConversations:needRemoveConversations deleteMessages:YES];
    }
}

#pragma mark - getter
- (UIView *)networkStateView
{
    if (_networkStateView == nil) {
        _networkStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.tableView.frame.size.width, 44)];
        _networkStateView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:199 / 255.0 blue:199 / 255.0 alpha:0.5];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_networkStateView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"messageSendFail"];
        [_networkStateView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, _networkStateView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), _networkStateView.frame.size.height)];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = [UIColor grayColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"network.disconnection", @"Network disconnection");
        [_networkStateView addSubview:label];
    }
    
    return _networkStateView;
}

- (UISearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [[EMSearchBar alloc] initWithFrame: CGRectMake(0, 64, self.view.frame.size.width, 44)];
        _searchBar.delegate = self;
        _searchBar.placeholder = NSLocalizedString(@"search", @"Search");
        _searchBar.backgroundColor = [UIColor colorWithRed:0.747 green:0.756 blue:0.751 alpha:1.000];
    }
    
    return _searchBar;
}

- (UIView *)headView
{
    if (!_headView) {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, mainScreenSize.width, 44)];
        UIButton * button1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, mainScreenSize.width/2, 44)];
        button1.tag = 101;
        [button1 setTitle:@"我的消息" forState:UIControlStateNormal];
        [button1.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
        [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button1 addTarget:self action:@selector(headViewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headView addSubview:button1];
        
        UIButton * button2 = [[UIButton alloc]initWithFrame:CGRectMake(mainScreenSize.width/2, 0, mainScreenSize.width/2, 44)];
        button2.tag = 102;
        [button2 setTitle:@"系统消息" forState:UIControlStateNormal];
        [button2.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
        [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button2 addTarget:self action:@selector(headViewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headView addSubview:button2];
        
        UILabel * line = [[UILabel alloc]initWithFrame:CGRectMake(mainScreenSize.width/4-45, 42, 90, 2)];
        line.tag = 103;
        [line setBackgroundColor:[UIColor blackColor]];
        [_headView addSubview:line];
    }
    
    return _headView;
}

-(void)headViewButtonClick:(UIButton *)btn{
    UILabel * labe = (UILabel *)[_headView viewWithTag:103];
    CGRect frame =  self.view.frame;
    self.view.frame = frame;
    if (btn.tag==101) {
        [labe setFrame:CGRectMake(mainScreenSize.width/4-45, 42, 90, 2)];
        [self.systemView setHidden:YES];
    }else{
        [self.systemView setHidden:NO];
        [labe setFrame:CGRectMake(mainScreenSize.width*3/4-45, 42, 90, 2)];
    }
}

- (EMSearchDisplayController *)searchController
{
    if (_searchController == nil) {
        _searchController = [[EMSearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
        _searchController.delegate = self;
        _searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _searchController.searchResultsTableView.tableFooterView = [[UIView alloc] init];
        
        __weak ConversationListController *weakSelf = self;
        [_searchController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            NSString *CellIdentifier = [EaseConversationCell cellIdentifierWithModel:nil];
            EaseConversationCell *cell = (EaseConversationCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            // Configure the cell...
            if (cell == nil) {
                cell = [[EaseConversationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            
            id<IConversationModel> model = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
            cell.model = model;
            
            cell.detailLabel.attributedText = [weakSelf conversationListViewController:weakSelf latestMessageTitleForConversationModel:model];
            cell.timeLabel.text = [weakSelf conversationListViewController:weakSelf latestMessageTimeForConversationModel:model];
            return cell;
        }];
        
        [_searchController setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return [EaseConversationCell cellHeightWithModel:nil];
        }];
        
        [_searchController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            [weakSelf.searchController.searchBar endEditing:YES];
            id<IConversationModel> model = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
            EMConversation *conversation = model.conversation;
            ChatViewController *chatController;
            if ([[RobotManager sharedInstance] isRobotWithUsername:conversation.conversationId]) {
                chatController = [[RobotChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
                chatController.title = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.conversationId];
            }else {
#ifdef REDPACKET_AVALABLE
                chatController = [[RedPacketChatViewController alloc]
#else
                                  chatController = [[ChatViewController alloc]
#endif
                                                    initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
                                  chatController.title = [conversation showName];
                                  }
                                  [weakSelf.navigationController pushViewController:chatController animated:YES];
                                  [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
                                  [weakSelf.tableView reloadData];
                                  }];
            }
            
            return _searchController;
        }
         
#pragma mark - EaseConversationListViewControllerDelegate
         
         - (void)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                                     didSelectConversationModel:(id<IConversationModel>)conversationModel
         {
             if (conversationModel) {
                 EMConversation *conversation = conversationModel.conversation;
                 if (conversation) {
                     if ([[RobotManager sharedInstance] isRobotWithUsername:conversation.conversationId]) {
                         RobotChatViewController *chatController = [[RobotChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
                         chatController.title = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.conversationId];
                         [self.navigationController pushViewController:chatController animated:YES];
                     } else {
                         //刷新用户数据
                         //                            NSString *username = [[EMClient sharedClient] currentUsername];
                         //                        NSLog(@"----da-username = %@",username);
                         //                         [self downLoadUserInfo:username];
                         
                         //                        [self downLoadUserInfo:conversationModel.title];
                         
                         
                         //界面跳转，刷新标题、
                         //                        [self setTitle:conversationModel.title];
                         
                         ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:conversationModel.title conversationType:EMConversationTypeChat];
                         chatController.patientUsername = conversationModel.title;

                         NSDictionary *peopleInfo = [AppConfig getPeopleInfo:conversationModel.title];
                         NSString *nickName = [NSString stringWithFormat:@"%@",[peopleInfo objectForKey:@"nickname"]];
                         if([AppConfig isStrNull:nickName]){
                             chatController.title = conversationModel.title;
                         }else{
                             chatController.title = nickName;
                         }
                         
                         //刷新数据
                         dispatch_async(dispatch_get_global_queue(0, 0),^{
                             //刷新列表未读数据显示
                             [self.tableView reloadData];
                             //刷新APP图标未读数据显示
                             MainViewController *mainVC = [[MainViewController alloc]init];
                             [mainVC setupUnreadMessageCount];
                         });
                         
                         [self.navigationController pushViewController:chatController animated:YES];
                         
                     }
                 }
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
                 
             }
         }
         
         -(void)downLoadUserInfo:(NSString *)loginName{
             NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:loginName,@"hnLoginName", nil];
             AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
             manager.responseSerializer = [AFHTTPResponseSerializer serializer];
             [manager POST:url_UserInfo parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 NSError * error;
                 NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
                 [self hideHud];
                 if (error) {
                     NSLog(@"====error1:%@",error);
                     return;
                 }
                 NSLog(@"==dict:%@",data);
                 NSString * code = [NSString stringWithFormat:@"%@",[data objectForKey:@"error"]];
                 if ([code isEqualToString:@"0"]) {
                     NSDictionary *userInfo = [data objectForKey:@"data"];
                     NSString *loginName = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"hnLoginName"]];
                     if ([AppConfig isNULL:loginName]) {
                         loginName = @"";
                     }
                     NSMutableDictionary *peopleDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:loginName,@"hnLoginName", nil];
                     NSString *head = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"hnHead"]];
                     if ([AppConfig isNULL:head]) {
                         head = @"";
                     }
                     [peopleDic setObject:head forKey:@"hnHead"];
                     NSString *nickName = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"hnNickName"]];
                     if ([AppConfig isNULL:nickName]) {
                         nickName = @"";
                     }
                     [peopleDic setObject:nickName forKey:@"hnNickName"];
                     NSLog(@"peopleDic = %@",peopleDic);
                     [AppConfig savePeopleInfo:peopleDic];
                 }else{
                     //            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"message"]];
                     //            [self showHint:info];
                 }
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
                 NSLog(@"====error:%@",error);
                 [self hideHud];
                 //        [self showHint:@"获取用户信息失败"];
             }];
         }
         
         -(void)setTitle:(NSString *)merchantPhone{
             //刷新加载头像数据
             NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:merchantPhone,@"hnLoginName", nil];
             AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
             manager.responseSerializer = [AFHTTPResponseSerializer serializer];
             [manager POST:url_UserInfo parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 NSError * error;
                 NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
                 [self hideHud];
                 if (error) {
                     NSLog(@"====error1:%@",error);
                     return;
                 }
                 NSLog(@"==dict:%@",data);
                 NSString * code = [NSString stringWithFormat:@"%@",[data objectForKey:@"error"]];
                 if ([code isEqualToString:@"0"]) {
                     NSDictionary *userInfo = [data objectForKey:@"data"];
                     ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:merchantPhone conversationType:EMConversationTypeChat];
                     chatController.title = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"hnNickName"]];
                     
                     //刷新数据
                     dispatch_async(dispatch_get_global_queue(0, 0),^{
                         //刷新列表未读数据显示
                         [self.tableView reloadData];
                         //刷新APP图标未读数据显示
                         MainViewController *mainVC = [[MainViewController alloc]init];
                         [mainVC setupUnreadMessageCount];
                     });
                     
                     [self.navigationController pushViewController:chatController animated:YES];
                 }else{
                     //            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"message"]];
                     //            [self showHint:info];
                 }
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
                 NSLog(@"====error:%@",error);
                 [self hideHud];
                 //        [self showHint:@"获取用户信息失败"];
             }];
         }
         
         
         
         
#pragma mark - EaseConversationListViewControllerDataSource
         
         - (id<IConversationModel>)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                                           modelForConversation:(EMConversation *)conversation
         {
             EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:conversation];
             if (model.conversation.type == EMConversationTypeChat) {
                 if ([[RobotManager sharedInstance] isRobotWithUsername:conversation.conversationId]) {
                     model.title = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.conversationId];
                 } else {
                     UserProfileEntity *profileEntity = [[UserProfileManager sharedInstance] getUserProfileByUsername:conversation.conversationId];
                     if (profileEntity) {
                         model.title = profileEntity.nickname == nil ? profileEntity.username : profileEntity.nickname;
                         model.avatarURLPath = profileEntity.imageUrl;
                     }
                 }
             } else if (model.conversation.type == EMConversationTypeGroupChat) {
                 NSString *imageName = @"groupPublicHeader";
                 if (![conversation.ext objectForKey:@"subject"])
                 {
                     NSArray *groupArray = [[EMClient sharedClient].groupManager getAllGroups];
                     for (EMGroup *group in groupArray) {
                         if ([group.groupId isEqualToString:conversation.conversationId]) {
                             NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.ext];
                             [ext setObject:group.subject forKey:@"subject"];
                             [ext setObject:[NSNumber numberWithBool:group.isPublic] forKey:@"isPublic"];
                             conversation.ext = ext;
                             break;
                         }
                     }
                 }
                 NSDictionary *ext = conversation.ext;
                 model.title = [ext objectForKey:@"subject"];
                 imageName = [[ext objectForKey:@"isPublic"] boolValue] ? @"groupPublicHeader" : @"groupPrivateHeader";
                 model.avatarImage = [UIImage imageNamed:imageName];
             }
             return model;
         }
         
         - (NSAttributedString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                         latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
         {
             NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:@""];
             EMMessage *lastMessage = [conversationModel.conversation latestMessage];
             if (lastMessage) {
                 NSString *latestMessageTitle = @"";
                 EMMessageBody *messageBody = lastMessage.body;
                 switch (messageBody.type) {
                     case EMMessageBodyTypeImage:{
                         latestMessageTitle = NSLocalizedString(@"图片", @"[image]");
                     } break;
                     case EMMessageBodyTypeText:{
                         // 表情映射。
                         NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                                     convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                         latestMessageTitle = didReceiveText;
                         if ([lastMessage.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
                             latestMessageTitle = @"[动画表情]";
                         }
                     } break;
                     case EMMessageBodyTypeVoice:{
                         latestMessageTitle = NSLocalizedString(@"语音消息", @"[voice]");
                     } break;
                     case EMMessageBodyTypeLocation: {
                         latestMessageTitle = NSLocalizedString(@"message.location1", @"[location]");
                     } break;
                     case EMMessageBodyTypeVideo: {
                         latestMessageTitle = NSLocalizedString(@"语音信息", @"[video]");
                     } break;
                     case EMMessageBodyTypeFile: {
                         latestMessageTitle = NSLocalizedString(@"message.file1", @"[file]");
                     } break;
                     default: {
                     } break;
                 }
                 
                 if (lastMessage.direction == EMMessageDirectionReceive) {
                     NSString *from = lastMessage.from;
                     UserProfileEntity *profileEntity = [[UserProfileManager sharedInstance] getUserProfileByUsername:from];
                     if (profileEntity) {
                         from = profileEntity.nickname == nil ? profileEntity.username : profileEntity.nickname;
                     }
                     latestMessageTitle = [NSString stringWithFormat:@"%@: %@", from, latestMessageTitle];
                 }
                 
                 NSDictionary *ext = conversationModel.conversation.ext;
                 if (ext && [ext[kHaveUnreadAtMessage] intValue] == kAtAllMessage) {
                     latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atAll", nil), latestMessageTitle];
                     attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
                     [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atAll", nil).length)];
                     
                 }
                 else if (ext && [ext[kHaveUnreadAtMessage] intValue] == kAtYouMessage) {
                     latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atMe", @"[Somebody @ me]"), latestMessageTitle];
                     attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
                     [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atMe", @"[Somebody @ me]").length)];
                 }
                 else {
                     attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
                 }
             }
             
             return attributedStr;
         }
         
         - (NSString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                          latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
         {
             NSString *latestMessageTime = @"";
             EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
             if (lastMessage) {
                 latestMessageTime = [NSDate formattedTimeFromTimeInterval:lastMessage.timestamp];
             }
             
             
             return latestMessageTime;
         }
         
#pragma mark - UISearchBarDelegate
         
         - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
         {
             [searchBar setShowsCancelButton:YES animated:YES];
             
             return YES;
         }
         
         - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
         {
             __weak typeof(self) weakSelf = self;
             [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:self.dataArray searchText:(NSString *)searchText collationStringSelector:@selector(title) resultBlock:^(NSArray *results) {
                 if (results) {
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [weakSelf.searchController.resultsSource removeAllObjects];
                         [weakSelf.searchController.resultsSource addObjectsFromArray:results];
                         [weakSelf.searchController.searchResultsTableView reloadData];
                     });
                 }
             }];
         }
         
         - (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
         {
             return YES;
         }
         
         - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
         {
             [searchBar resignFirstResponder];
         }
         
         - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
         {
             searchBar.text = @"";
             [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
             [searchBar resignFirstResponder];
             [searchBar setShowsCancelButton:NO animated:YES];
         }
         
#pragma mark - public
         
         -(void)refresh
         {
             [self refreshAndSortView];
         }
         
         -(void)refreshDataSource
         {
             [self tableViewDidTriggerHeaderRefresh];
         }
         
         - (void)isConnect:(BOOL)isConnect{
             if (!isConnect) {
                 self.tableView.tableHeaderView = _networkStateView;
             }
             else{
                 self.tableView.tableHeaderView = nil;
             }
             
         }
         
         - (void)networkChanged:(EMConnectionState)connectionState
         {
             if (connectionState == EMConnectionDisconnected) {
                 self.tableView.tableHeaderView = _networkStateView;
                 self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(65,  self.tableView.frame.size.width, self.tableView.frame.size.height - 115, 60)];
             }
             else{
                 self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(65,  self.tableView.frame.size.width, self.tableView.frame.size.height - 115, 60)];
                 self.tableView.tableHeaderView = nil;
             }
         }
         
#pragma mark - 头部轮播图
         
         -(void)drawView{

             
             //    //设置轮播图
             [self setAdsVC:nil];
             //
             //
             //    //设置搜索
             //    [self setSearchBtn];
             
             
         }
         
         
         -(void)initData{
             //获取轮播图数据
             self.arrayImages = [[NSMutableArray alloc]init];
             [self getAdsImage];
             
             self.cur = 1;//分页初始赋值
             
             //    [self getDoctorData];
               [self getUserInfo];
             
             
         }
         
         
         -(void)setAdsVC:(NSMutableArray *)imageArr{
             _contentHeight = 0;
             if (!imageArr) {
                 //       self.arrayImages = [NSMutableArray arrayWithObjects:@"ads_1.png",@"54521417567978.png", nil];
             }else{
                 self.arrayImages = imageArr;
             }
             
             self.adsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Width*3/5)];
        
             [self.view addSubview:self.adsView];
   
             CGFloat height = self.adsView.frame.size.height;
             CGFloat width = self.adsView.frame.size.width;
             _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width,height)];
             [_scrollView setPagingEnabled:YES];
             _scrollView.showsHorizontalScrollIndicator = NO;
             _scrollView.showsVerticalScrollIndicator = NO;
             [_scrollView setDelegate:self];
             [_scrollView setBackgroundColor:[UIColor lightGrayColor]];
             
             //ContentSize 这个属性对于UIScrollView挺关键的，取决于是否滚动。
             [_scrollView setContentSize:CGSizeMake(width * [self.arrayImages count], height)];
             [self.adsView addSubview:self.scrollView];
             
             [self.scrollView setBounces:YES];
             
             _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width/2-80, self.scrollView.frame.size.height - 20, 160, 20)];
             //    [_pageControl setBackgroundColor:[UIColor blackColor]];
             
             _pageControl.currentPage = 0;
             _pageControl.numberOfPages = [self.arrayImages count];
             [_pageControl addTarget:self action:@selector(chagePage:) forControlEvents:UIControlEventValueChanged];
             [self.adsView addSubview:self.pageControl];
             
             _viewController = [[NSMutableArray alloc] init];
             
             for (NSInteger i = 0; i < [self.arrayImages count]; i++) {
                 [_viewController addObject:[NSNull null]];
             }
             
             //加载每张图
             for (NSInteger i = 0; i<self.arrayImages.count; i++) {
                 [self loadScrollViewPage:i];
             }
             
             //    _timer = [NSTimer scheduledTimerWithTimeInterval:self.arrayImages.count*2 target:self selector:@selector(scrollPages) userInfo:nil repeats:YES];
             
             
         }
         
         
         
         
         
#pragma mark - 轮播图展现
         -(void)loadScrollViewPage:(NSInteger)page
        {
            if (page >= self.arrayImages.count) {
                return;
            }
            
            UIImageView *adsImageView = [self.viewController objectAtIndex:page];
            if ((NSNull *)adsImageView == [NSNull null])
            {
                adsImageView = [[UIImageView alloc] init];
                [self.viewController replaceObjectAtIndex:page withObject:adsImageView];
            }
            
            if (adsImageView.superview == nil) {
                CGRect frame = self.scrollView.frame;
                frame.origin.x = CGRectGetWidth(frame) * page;
                frame.origin.y = 0;
                adsImageView.frame = frame;
                
                [self.scrollView addSubview:adsImageView];
                
                NSLog(@"%@",self.arrayImages);
                
                if (self.arrayImages) {
                    NSString *imageStr = [NSString stringWithFormat:@"%@%@",url_Base,[[self.arrayImages objectAtIndex:page] objectForKey:@"advertImg"]];
                    NSLog(@"%@",imageStr);
                    
                    [adsImageView sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"ad_0.png"]];
                }
                
                
            }
        }
         
         
         -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
        {
            CGFloat pageWidth = CGRectGetWidth(self.scrollView.frame);
            NSInteger page = floor((self.scrollView.contentOffset.x -pageWidth/2)/pageWidth) ;
            if (self.scrollView.contentOffset.x<0) {
                _pageControl.currentPage = self.arrayImages.count - 1;
            }else if(self.scrollView.contentOffset.x > (self.arrayImages.count - 1)*kScreen_Width){
                _pageControl.currentPage = 0;
            }else{
                _pageControl.currentPage = page + 1;
            }
            [self loadScrollViewPage:page];
            //    [self loadScrollViewPage:page-1];
            //    [self loadScrollViewPage:page];
            //    [self loadScrollViewPage:page+1];
        }
         
         //- (IBAction)changePage:(id)sender
         //{
         //    NSInteger page = self.pageControl.currentPage;
         //
         //    [self loadScrollViewPage:page - 1];
         //    [self loadScrollViewPage:page];
         //    [self loadScrollViewPage:page + 1];
         
         //    CGRect bounds = self.scrollView.bounds;
         //    bounds.origin.x = Kwidth * page - 1;
         //    bounds.origin.y = 0;
         //    [self.scrollView scrollRectToVisible:bounds animated:YES];
         //}
         
         
         //NSTimer
         -(void)scrollPages{
             //    ++self.pageControl.currentPage;
             CGFloat pageWidth = CGRectGetWidth(self.scrollView.frame);
             if (isFromStart) {
                 [self.scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
                 _pageControl.currentPage = 0;
             }
             else
             {
                 _pageControl.currentPage ++;
                 
                 [self.scrollView setContentOffset:CGPointMake(pageWidth*_pageControl.currentPage, self.scrollView.bounds.origin.y)];
                 
                 [self loadScrollViewPage:_pageControl.currentPage];
             }
             if (_pageControl.currentPage == _pageControl.numberOfPages - 1) {
                 isFromStart = YES;
             }
             else
             {
                 isFromStart = NO;
             }
         }
         
#pragma mark - 轮播图 UIPageControl
         -(void)chagePage:(UIPageControl *)pageControl
        {
            //    _pageControl.currentPage
        }
         
         
#pragma mark - scrollViewDelegate
         // contentScrollView 已经滑动
         - (void)scrollViewDidScroll:(UIScrollView *)scrollView
        {
            //    CGFloat offset = _noListNormalH - 58 - 36 - 36;
            //    CGFloat contentScrolloffectY = _contentScrollView.contentOffset.y;
            //    if (_noListNormalH != 0) {
            //        if (contentScrolloffectY >= offset) {
            //            self.srarchView.alpha = 1;
            //            [self.listHeadView setHidden:YES];
            //            [self.listOtherHeadView setHidden:NO];
            //            [self.searchBackground setBackgroundColor:RGB(244, 244, 244)];
            //        }else{
            //            self.srarchView.alpha = contentScrolloffectY/offset;
            //            [self.listHeadView setHidden:NO];
            //            [self.listOtherHeadView setHidden:YES];
            //            [self.searchBackground setBackgroundColor:RGB(255, 255, 255)];
            //        }
            //    }
            
            //    NSLog(@"scrollViewDidScroll");
        }
         
         // contentScrollView 开始拖动
         - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
        {
            //    NSLog(@"scrollViewWillBeginDragging");
        }
         
         // contentScrollView 结束拖动
         - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
        {
            //    NSLog(@"scrollViewDidEndDragging");
        }
         
         
#pragma mark - 初始化数据--轮播图
         
         -(void)getAdsImage{
             NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
             NSLog(@"param = %@",param);
             
             
             AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
             manager.responseSerializer = [AFHTTPResponseSerializer serializer];
             [manager POST:url_Advert_list parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 NSError * error;
                 NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
                 [self hideHud];
                 if (error) {
                     NSLog(@"====error1:%@",error);
                     [self showHint:@"获取轮播图失败"];
                     NSLog(@"==dict:%@",data);
                     return;
                 }
                 NSLog(@"==dict:%@",data);
                 
                 NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
                 if ([result isEqualToString:@"1"]) {
                     NSMutableArray * obj = [NSMutableArray arrayWithArray:[data objectForKey:@"obj"]];
                     NSLog(@"------obj = %@",obj);
                     
                     _timer = [NSTimer scheduledTimerWithTimeInterval:obj.count*2 target:self selector:@selector(scrollPages) userInfo:nil repeats:YES];
                     
                     [_adsView removeFromSuperview];
                     
                     
                     
                     //    //设置轮播图
                     [self setAdsVC:obj];
                     //
                     //
                     //    //设置搜索
                     //            [self setSearchBtn];
                     
                     
                     
                     
                 }else{
                     NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
                     if ([info isEqualToString:msg_InvalidLoginInformation]) {
                         
                         [AppConfig removeUserInfo];
                         
                         [[EMClient sharedClient] logout:YES];
                         [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                         
                         HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                         
                         [self.navigationController pushViewController:loginVC animated:YES];
                     }

                     [self showHint:info];
                 }
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
                 NSLog(@"====error:%@",error);
                 [self hideHud];
                 [self showHint:@"获取轮播图失败"];
             }];
             
             
         }
         
         
         -(void)getUserInfo{
             NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
             
             NSLog(@"param = %@",param);
             
             
             AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
             manager.responseSerializer = [AFHTTPResponseSerializer serializer];
             [manager POST:url_userInfo_detail parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 NSError * error;
                 NSLog(@"responseObject = %@",responseObject);
                 
                 NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
                 [self hideHud];
                 if (error) {
                     NSLog(@"====error1:%@",error);
                     [self showHint:@"获取用户信息失败"];
                     NSLog(@"==dict:%@",data);
                     return;
                 }
                 NSLog(@"==dict:%@",data);
                 
                 NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
                 if ([result isEqualToString:@"1"]) {
                     NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:[data objectForKey:@"obj"]];
                     NSLog(@"------obj = %@",userInfo);
                     [Util addUserId:[NSString stringWithFormat:@"%@",[userInfo objectForKey:@"userId"]]];
                     NSLog(@"fsdkgj %@",[Util getUserId]);
                     
                     
                     NSString *userImageStr = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"photo"]];
                     if ([AppConfig isNULL:userImageStr]) {
                         userImageStr = @"null";
                     }
                     NSString *userNickname = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"nickname"]];
                     if ([AppConfig isNULL:userNickname]) {
                         userImageStr = @"未设置";
                     }
                     NSString *userUserName = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"username"]];
                     if ([AppConfig isNULL:userUserName]) {
                         userImageStr = @"未设置";
                     }
                     NSDictionary *saveDic = [NSDictionary dictionaryWithObjectsAndKeys:userImageStr,@"photo",userUserName,@"hnLoginName",userNickname,@"nickname", nil];
                     
                     [AppConfig saveUserInfo:saveDic];
                     
                     
                 }else{
                     NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
                     if ([info isEqualToString:msg_InvalidLoginInformation]) {
                         
                         [AppConfig removeUserInfo];
                         
                         [[EMClient sharedClient] logout:YES];
                         [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                         
                         HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                         
                         [self.navigationController pushViewController:loginVC animated:YES];
                     }

                     [self showHint:info];
                 }
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
                 NSLog(@"====error:%@",error);
                 [self hideHud];
                 [self showHint:@"获取用户信息失败"];
             }];
             
             
         }
         
         @end
